package com.xpfirst.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.xpfirst.ActivityManage;

import android.util.Log;

public class SocketClient implements Runnable{
	Socket socket=null;

	public void write(String str){
		if(socket != null){
			if(socket.isConnected()){
				try{
					socket.sendUrgentData(0); 
					PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
					out.println(str);
				}catch(IOException e){
					close();
				}
			}
			else{
				close();
			}
		}
	}
	public void run() {
		while(true){
			if(socket != null){
				if(socket.isConnected()){
					try{
						InputStream inputStream = socket.getInputStream();
						int i = inputStream.available();
						InputStreamReader input = new InputStreamReader(inputStream);
						BufferedReader br=new BufferedReader(input);
						String mstr = br.readLine();
						if(mstr != null){
			                ActivityManage.sendMsg(4, "writeMsg", mstr);
							mstr = null;
						}
					}catch(IOException e){
					}
				}
			}
		}
	}
	public void close(){
		String host = socket.getInetAddress().getHostAddress();
		try{
			socket.close();
			socket = null;
		}catch(IOException e){
			socket = null;
		}
		SocketManage.removeSocketClient(host);
	}
}
